<?php

namespace App\Http\Controllers\Api\V1;

use Dingo\Api\Exception\StoreResourceFailedException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Storage;
use Validator;

class ImageController extends Controller
{
    const PUBLIC_DIR = 'public/public/images/';
    const SAVE_DIR = 'public/user/images/'; // 实际是 storage/app/public/user/images
	const SHOW_DIR = 'storage/user/images/'; // url 中的 domain/storage/user/images/

    /**
     * @SWG\Get(
     *     summary="公共图片列表",
     *     path="/image/public",
     *     description="获取公共图片列表",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function public_images(Request $request)
    {
        // echo asset('storage/abc.txt');die;// http://www.engine.dakala/storage/abc.txt
        $dir = self::PUBLIC_DIR;

        $paths = Storage::allFiles($dir);
        // 找的是 storage\app\public\public\images 下面的图片
        foreach ($paths as &$image) {
            $image = str_replace('public/', env('APP_URL') . 'storage/', $image);
        }

        return $paths ? $paths : [];
    }

    /**
     * @SWG\Get(
     *     summary="用户图片列表",
     *     path="/image",
     *     description="获取用户图片列表",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function index(Request $request)
    {
        $path = self::SAVE_DIR . substr(md5($request->user()->id), 8, 16) . '/';

        $paths = Storage::allFiles($path);

        foreach ($paths as &$image) {
            $image = str_replace('public/', env('APP_URL') . 'storage/', $image);
        }

        return $paths ? $paths : [];
    }

    /**
     * @SWG\Post(
     *     summary="用户上传图片",
     *     path="/image",
     *     description="用户上传图片",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="file-image",
     *         in="query",
     *         description="图片(base64)",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function store(Request $request)
    {
        // print_r($_FILES);
        // exit;
        $rules = [
            'file-image' => ['required']
        ];
        $messages = [
            'file-image.required' => '请上传图片'
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            throw new StoreResourceFailedException('create error', $validator->errors());
        }

        $types = ['jpg', 'gif', 'png', 'jpeg'];        

        // 综合性代码
        // 添加了批量上传文件的处理，同时兼顾了单个文件的上传
        $image = $request->file('file-image');
        if (!is_array($image)) {
            $images = [$image];
        } else {
            $images = $image;
        }
        $paths = [];
        foreach ($images as $image) {
            if ($image->isValid()) {
                // 获取文件相关信息
                $ext = $image->getClientOriginalExtension();     // 扩展名
                $realPath = $image->getRealPath();   //临时文件的绝对路径

                if (!in_array($ext, $types)) {
                    throw new StoreResourceFailedException('format error');
                }

                // 上传文件
                $path = substr(md5($request->user()->id), 8, 16) . date('/Y/md/');
                $filename = uniqid() . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                Storage::disk('local')->put(self::SAVE_DIR . $path . $filename, file_get_contents($realPath));
                // return ['path' => env('APP_URL') . self::SHOW_DIR . $path . $filename];
                $paths[] = env('APP_URL') . self::SHOW_DIR . $path . $filename;
            } else {
                throw new StoreResourceFailedException('format error');
            }
        }
        // 如果上传单个文件，path 的值是一个字符串
        // 如果上传多个文件，path 的值是一个数组
        return ['path' => ((count($paths) == 1) ? $paths[0] : $paths)];
    }

    /**
     * @SWG\Delete(
     *     summary="用户删除图片",
     *     path="/image",
     *     description="用户删除图片",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="image",
     *         in="query",
     *         description="图片名称(只需要文件名)",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function destroy(Request $request)
    {
        $imageArray = explode('/', $request->image);
        $image = $imageArray[count($imageArray) - 2] . '/';
        $image .= $imageArray[count($imageArray) - 1];

        $path = self::SAVE_DIR . substr(md5($request->user()->id), 8, 16) . '/';

        Storage::delete($path . $image);

        return ['success' => true];
    }
}
